package com.jams.goodox.activity.qa.parent;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.mine.buy.RecordNextStepActivity;
import com.jams.goodox.activity.parent.ParentQuestionAnswerDetailActivity;
import com.jams.goodox.activity.qa.entity.Question;
import com.jams.goodox.adapter.lfadapter.CommonRecycleViewAdapter;
import com.jams.goodox.adapter.lfadapter.LFRecyclerViewHolder;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.TimeUtils;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.CustomPopWindow;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import me.leefeng.lfrecyclerview.OnItemClickListener;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 家长的回答，
 */
public class ParentAnswerListActivity extends BaseActivity  implements
        OnItemClickListener, LFRecyclerView.LFRecyclerViewListener,
        LFRecyclerView.LFRecyclerViewScrollChange{


    private static final String TAG = ParentAnswerListActivity.class.getSimpleName();
    @Bind(R.id.recycleView)
    LFRecyclerView recyclerView;

    @Bind(R.id.grid_type)
    TextView grid_type;


    private CommonRecycleViewAdapter pAdapter;
    private List<Question> list = new ArrayList<>();

    private boolean status = false;//判断加载成功还是失败
    private boolean isRefresh = true;

    CustomPopWindow popWindow;
    int section = 2;//问答状态(0未回答，1已回答，2 所有)

    private int pageNum = 1;

    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            if (msg.what == 1) {
                if (isRefresh) {
                    recyclerView.stopRefresh(status);
                    pAdapter.notifyDataSetChanged();
                } else {
                    recyclerView.stopLoadMore();
                    pAdapter.notifyDataSetChanged();
                }
            }
        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.qa_list_activity;
    }

    @Override
    protected void init() {
        setTitleVisibility(false);
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部
//        StyleUtil.titleBackKeyWithRightTextViewListener(this, "我的回答", "全部 >", new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //qStartActivity(RecordNextStepActivity.class);
//                showPoP(v);
//
//            }
//        });


        grid_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPoP(v);
            }
        });


        recyclerView.setLoadMore(true);
        recyclerView.setRefresh(true);
        recyclerView.setNoDateShow();
        recyclerView.setAutoLoadMore(false);
        recyclerView.setOnItemClickListener(this);
        recyclerView.setLFRecyclerViewListener(this);
        recyclerView.setScrollChangeListener(this);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        pAdapter = new CommonRecycleViewAdapter(recyclerView, list, R.layout.wendajx_item) {
            @Override
            public void bindConvert(LFRecyclerViewHolder holder, int position, Object item, boolean isScrolling) {

                Log.d(TAG, " 9999 = " + item.toString());
                Question jxQuestion = (Question) item;
                //问答状态(0未回答，1已回答，2已查看答案)
                holder.setText(R.id.nickname, jxQuestion.getNickName());
                holder.setText(R.id.time, TimeUtils.getDateToString(jxQuestion.getCreateTime()));
                holder.setText(R.id.descr,jxQuestion.getDescr());
                holder.loadImage(R.id.image, jxQuestion.getImgPath());

                if(jxQuestion.getQueState() == 0){
                    holder.setText(R.id.status,"未回答");
                }else {
                    holder.setText(R.id.status,"已回答");
                }

            }

        };

        recyclerView.setFootText("");

        recyclerView.setAdapter(pAdapter);

        requestData();
    }


    private void showPoP(View view) {

        //创建并显示popWindow
        if(null == popWindow){
            View viewPop = LayoutInflater.from(getContext()).inflate(R.layout.pop_layout1,null);
            popWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                    .setView(viewPop)
                    .setFocusable(true)
                    .setOutsideTouchable(true)
                    .create();

            viewPop.findViewById(R.id.all).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popWindow.dissmiss();
                    //getData();//
                    section = 2;
                    grid_type.setText("全部");
                    //StyleUtil.setRightTxt(ParentAnswerListActivity.this,"全部 >");
                    requestData();
                }
            });

            viewPop.findViewById(R.id.yihuida).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popWindow.dissmiss();
                    //getData();//已回答
                    section = 1;
                    grid_type.setText("已回答");
                    //StyleUtil.setRightTxt(ParentAnswerListActivity.this,"已回答 >");
                    requestData();
                }
            });


            viewPop.findViewById(R.id.weihuida).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popWindow.dissmiss();
                    //getData();//未回答
                    section = 0;
                    grid_type.setText("未回答");
                    //StyleUtil.setRightTxt(ParentAnswerListActivity.this,"未回答 >");
                    requestData();
                }
            });
        }

        popWindow.showAsDropDown(view,0,10);

    }

    public void requestData() {
        clearMap();

//        params.put("requestData", "{memberId:" + SePref.getId() + "}");

        StringBuilder pData = new StringBuilder();
        pData.append("\"memberId\":" + SePref.getId())
                .append(",\"pageNum\":" + pageNum)
                .append(",\"pageSize\":" + 30);

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);

        Call<ResponseBody> example;
        if(section == 0){
            example = createCallService(LoginService.class).ownAsk(body);
        }else if(section == 1){
            example = createCallService(LoginService.class).ownAnswered(body);
        }else{
            example = createCallService(LoginService.class).own(body);
        }

        showLoading();
        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, " data own= " + data);
                    JSONObject jsonObject = new JSONObject(data);

                    if (200 == jsonObject.getInt("code")) {
                        status = true;
                        if (isRefresh) {
                            list.clear();
                        }
                        String responseData = jsonObject.getString("responseData");
                        JSONArray jsonArray = new JSONArray(responseData);
                        if (null == jsonArray || jsonArray.length() <= 0) {
                            //ToastUtil.show("没有更多数据");
                            handler.sendEmptyMessage(1);
                            return;
                        }

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);

                            Question question = new Question();
                            question.setImgPath(object.getString("imgPath"));
                            question.setId(object.getInt("id"));
                            question.setQueState(object.getInt("queState"));
                            question.setNickName(object.getString("nickName"));
                            question.setDescr(object.getString("descr"));
                            question.setCreateTime(object.getLong("createTime"));
                            list.add(question);
                            Log.d(TAG, "question = " + question.toString());

//                            if(section == 2){
//                                Question question = new Question();
//                                question.setImgPath(object.getString("imgPath"));
//                                question.setId(object.getInt("id"));
//                                question.setQueState(object.getInt("queState"));
//                                question.setNickName(object.getString("nickName"));
//                                question.setDescr(object.getString("descr"));
//                                question.setCreateTime(object.getLong("createTime"));
//
//                                list.add(question);
//                                Log.d(TAG, "question = " + question.toString());
//                            }else {
//                                if(object.getInt("queState") == section ){
//                                    Question question = new Question();
//                                    question.setImgPath(object.getString("imgPath"));
//                                    question.setId(object.getInt("id"));
//                                    question.setQueState(object.getInt("queState"));
//                                    question.setNickName(object.getString("nickName"));
//                                    question.setDescr(object.getString("descr"));
//                                    question.setCreateTime(object.getLong("createTime"));
//
//                                    list.add(question);
//                                    Log.d(TAG, "question = " + question.toString());
//                                }
//                            }

                        }


                    } else {
                        ToastUtil.show("网络异常！");
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }

                handler.sendEmptyMessage(1);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                status = false;
                Log.d(TAG, "onFailure = " + t.getMessage());
                handler.sendEmptyMessage(1);
            }
        });

    }


    @Override
    public void onRecyclerViewScrollChange(View view, int i, int i1) {

    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        isRefresh = true;
        requestData();
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        isRefresh = false;
        requestData();
    }

    @Override
    public void onClick(int position) {
        Question question = list.get(position);
//        Intent intent = new Intent(this, ParentQuestionAnswerDetailActivity.class);
//        intent.putExtra("questionId", question.getId());
//        startActivity(intent);


        Intent intent = new Intent(this, ParentQuestionAnswerDetailActivity.class);
        intent.putExtra("question",question);
        startActivity(intent);
    }

    @Override
    public void onLongClick(int po) {

    }
}
